package com.anjiplus.template.gaea.business.modules.quartzReport.task;


import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class SyncData {
    // 控制中心服务器地址
    //private static String ipAndPort = "https://135.32.15.55:4433";
    private static String APPID = "3396355";
    private static String SecretKey = "b85b57fbae684d8b9f96886cd968472a";


    /**
     * 处理body参数
     */
    private static String getAsciiSort(Map map) {
        String[] srotedKeys = (String[]) map.keySet().toArray(new String[]{});
        Arrays.sort(srotedKeys);
        StringBuilder s2 = new StringBuilder();
        for (String key : srotedKeys) {
            if (map.get(key).equals(1)){
                s2.append("\"").append(key).append("\"").append(":").append(map.get(key))
                        .append(",");
            }else {
                s2.append("\"").append(key).append("\"").append(":").append("\"").append(map.get(key)).append("\"")
                        .append(",");
            }

        }
        s2.deleteCharAt(s2.length() - 1);
        return "{" + s2.toString() + "}";
    }

    /**
     * 处理query参数
     */
    private static String getAsciiSort2(Map map) {
        String[] srotedKeys = (String[]) map.keySet().toArray(new String[]{});
        Arrays.sort(srotedKeys);
        StringBuilder s2 = new StringBuilder();
        for (String key : srotedKeys) {
            s2.append(key).append("=").append(map.get(key)).append("&");
        }
        s2.deleteCharAt(s2.length() - 1);
        return s2.toString();
    }

    /**
     * 获取header
     *
     * @param pathname：apiUrl
     * @param query：query参数
     * @param body：body参数
     * @return 签名、时间戳、APIID、nonce
     */
    public static HashMap<String, Object> getHeader(String pathname, Map query, Map body) {
        HashMap<String, Object> hm = new HashMap();
        // 签名串
        String qmc = pathname;
        if ((null != query && !query.isEmpty()) || (null != body && !body.isEmpty())) {
            qmc = pathname + "?";
            if (null != query && !query.isEmpty()) {
                qmc = qmc + getAsciiSort2(query);
                if (null != body && !body.isEmpty()) {
                    qmc = qmc + "&" + getAsciiSort(body);
                }
            } else {
                qmc = qmc + getAsciiSort(body);
            }
            String bodyString=qmc.replaceAll(pathname,"");
            bodyString=bodyString.replace("?","");
            hm.put("body", bodyString);
        }
        String nonce = getNonce(8) + "-" + getNonce(4) + "-" + getNonce(4) + "-" + getNonce(4) + "-" + getNonce(12);
        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        // 签名密钥
        String qmmy = "appId=" + APPID + "&appSecret=" + SecretKey + "&timestamp=" + timeStamp + "&nonce=" + nonce;

        // 签名
        String qm = "";
        try {
            System.out.println("签名串：" + qmc);
            System.out.println("签名密钥：" + qmmy);
            qm = HMACSHA256(qmc, qmmy);
        } catch (Exception e) {
            e.printStackTrace();
        }

        hm.put("x-ca-sign", qm);
        hm.put("x-ca-timestamp", timeStamp);
        hm.put("x-ca-key", APPID);
        hm.put("x-ca-nonce", nonce);
        return hm;
    }

    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString();
    }

    /**
     * 字符串转换成为16进制(无需Unicode编码)
     *
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString().trim();
    }

    /**
     * 16进制直接转换成为字符串(无需Unicode解码)
     *
     * @param hexStr
     * @return
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * 获取随机数
     */
    public static String getNonce(int length) {
        String a = "abcd33456789";
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int index = new Random().nextInt(a.length());
            result.append(a.charAt(index));
        }
        return result.toString();
    }

    public static void main(String[] orgs) {
        HashMap<String,Object> mmp = new HashMap<>();
        mmp.put("status", 1);
        mmp.put("name", "testUser12");
        mmp.put("description", "");
        mmp.put("password", "]t4V9J1b");
        mmp.put("email", "");
        mmp.put("phone", "13439483004");
        mmp.put("groupId", "root");
        mmp.put("expiredTime", "0");
        mmp.put("inheritGroup", 1);
        Map hh = getHeader("/api/v2/localUser/createUser", null, mmp);
        System.out.println("APP密钥：" + SecretKey);
        System.out.println("x-ca-sign:" + hh.get("x-ca-sign").toString());
        System.out.println("x-ca-timestamp:" + hh.get("x-ca-timestamp").toString());
        System.out.println("x-ca-key:" + hh.get("x-ca-key").toString());
        System.out.println("x-ca-nonce:" + hh.get("x-ca-nonce").toString());


    }
}
